import {
  getProductCategory,
  getProductDetail,
  getProductList,
} from '@/services/ant-design-pro/product';
import { useDebounceFn } from '@ant-design/pro-components';
import { Button, Card, Col, Empty, Form, InputNumber, Modal, Radio, Row, Select } from 'antd';
import { useEffect, useState } from 'react';
import Zoom from 'react-medium-image-zoom';

const { Option } = Select;

const AddOrderProductCard = ({ onChange, }) => {
  const [productList, setProductList] = useState([]);
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [secondaryModalVisible, setSecondaryModalVisible] = useState(false);
  const [selectedItems, setSelectedItems] = useState([]);
  const [skuOptions, setSkuOptions] = useState([]);
  const [productDetail, setProductDetail] = useState(null);
  const [productSkuOptions, setProductSkuOptions] = useState([]);
  const [searchParams, setSearchParams] = useState({});
  const [collectionOptions, setCollectionOptions] = useState([]);
  const [productConfirmForm] = Form.useForm();

  console.log('selectedItems', selectedItems)

  const initProductList = async (params = {}) => {
    const resp = await getProductList({ ...params, status: 1, page: 1, pageSize: 100 });
    const { list } = resp?.data;
    console.log('[list]', list);
    setProductList(list);
  };

  const initProductDetail = async (id) => {
    const resp = await getProductDetail(id);
    const data = resp?.data;
    console.log('[data]', data);
    const options = [];
    data?.variants?.forEach((variant) => {
      options.push({
        label: `${variant?.attributeValues?.[0]?.value} - ${variant.price}`,
        value: variant.id,
      });
    });
    setProductSkuOptions(options);
    setProductDetail(data);
  };

  const initCollection = async () => {
    const resp = await getProductCategory({
      page: 1,
      pageSize: 100,
    });

    const { list } = resp?.data;
    let options = list.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });

    options = [{ value: null, label: '全部' }, ...options];
    setCollectionOptions(options);
  };

  useEffect(() => {
    initCollection();
    initProductList();
  }, []);

  const handleAddClick = async (record) => {
    setSelectedProduct(record);
    await initProductDetail(record?.id);
    setSecondaryModalVisible(true);
  };

  const handleSecondaryModalOk = (values) => {
    const selectedSku = productDetail?.variants?.find((option) => option.id === values.variantId);
    console.log('[values]', values);
    const newItem = {
      productId: selectedProduct.id,
      productName: selectedProduct.title,
      variantId: values.variantId,
      variantName: selectedSku?.attributeValues?.[0]?.value,
      quantity: values.quantity,
    };
    setSelectedItems((prevItems) => [...prevItems, newItem]);
    setSecondaryModalVisible(false);
    handleChange([...selectedItems, newItem]);
    productConfirmForm.resetFields();
  };

  const handleDeleteItem = (index) => {
    setSelectedItems(selectedItems.filter((_, i) => i !== index));
    handleChange(selectedItems.filter((_, i) => i !== index));
  };

  const handleChange = (vals) => {
    if (onChange) onChange(vals);
  };

  const { run: handleSearch } = useDebounceFn((params) => {
    setSearchParams({ ...searchParams, ...params });
    return initProductList({ ...searchParams, ...params });
  }, 500);

  const columns = [
    {
      title: '名称',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category) => category?.name,
    },
    {
      title: '图片',
      dataIndex: 'image',
      key: 'name',
      render: (image) => (
        <Zoom>
          <img src={image} style={{ width: 28 }} />
        </Zoom>
      ),
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="primary" onClick={() => handleAddClick(record)}>
          添加
        </Button>
      ),
    },
  ];

  return (
    <>
      <Card className={'mt20'} title="商品列表">
        <Row gutter={16}>
          <Col span={16}>
            <Row gutter={10}>
              {/* <Col>
                <Input
                  placeholder="请输入商品名称"
                  onChange={(e) => {
                    handleSearch({
                      keyword: e.target.value,
                    });
                  }}
                ></Input>
              </Col> */}
              <Radio.Group
                size="large"
                onChange={(e) => {
                  handleSearch({
                    category: e.target.value,
                  });
                }}
                optionType="button"
                options={collectionOptions}
                buttonStyle="solid"
              ></Radio.Group>
            </Row>

            <Row gutter={[20, 20]} className="mt20">
              {productList?.map((product) => {
                return (
                  <Col key={product.id} span={6}>
                    <div className="flex flex-col items-center justify-center " style={{
                      boxShadow: '0 0 10px 0 rgba(0, 0, 0, 0.1)',
                      borderRadius: 10,
                      overflow: 'hidden',
                      cursor: 'pointer',
                    }}
                      onClick={() => handleAddClick(product)}
                    >
                      <img
                        src={product?.image || 'https://pic1.imgdb.cn/item/678b9db2d0e0a243d4f57a2f.png'}
                        alt=""
                        className="w100"
                        style={{ height: '120px', objectFit: 'cover' }}
                      />
                      {/* </Zoom> */}
                      <div className="mt10 mb10 text-center" style={{ fontSize: 18, fontWeight: 'bold' }}>{product.title}</div>
                    </div>
                  </Col>
                );
              })}
            </Row>
            {/* <Table columns={columns} dataSource={productList} rowKey="id" className="mt10" /> */}
          </Col>
          <Col span={8}>
            <Card title="已选商品">
              {selectedItems.map((item, index) => (
                <Row key={index} align={'middle'} justify="space-between" className="mt10">
                  <Col span={5}>{item.productName}</Col>
                  <Col span={4}>{item.variantName}</Col>
                  <Col span={3} style={{ whiteSpace: 'nowrap' }}>数量: {item.quantity}</Col>
                  <Col span={4}>
                    <Button type="primary" danger onClick={() => handleDeleteItem(index)}>
                      删除
                    </Button>
                  </Col>
                </Row>
              ))}

              {selectedItems.length === 0 && <Empty description="请选择商品" />}
            </Card>
          </Col>
        </Row>
      </Card>

      <Modal
        title="商品确认"
        visible={secondaryModalVisible}
        onCancel={() => {
          setSecondaryModalVisible(false);
          productConfirmForm.resetFields();
        }}
        footer={null}
        destroyOnClose
        zIndex={9999}
      >
        <Card>
          <Form onFinish={handleSecondaryModalOk} form={productConfirmForm}>
            {productDetail?.variants?.length > 0 && (
              <Form.Item
                label="SKU选择"
                name="variantId"
                rules={[{ required: true, message: '请选择SKU' }]}
              >
                <Radio.Group
                  block
                  options={productSkuOptions}
                  defaultValue="Apple"
                  optionType="button"
                  buttonStyle="solid"
                />
              </Form.Item>
            )}
            <div className="flex">
              <Form.Item
                name="quantity"
                label="数量"
                rules={[{ required: true, message: '请输入数量' }]}
              >
                {/* <NumPad.Number
                onChange={(value) => console.log('value', value)}
                placeholder={''}
                zIndex={100000}
              /> */}
                <InputNumber min={1} />
              </Form.Item>
              <div className="ml10">
                <Button
                  onClick={() => {
                    productConfirmForm.setFieldsValue({
                      quantity: (productConfirmForm.getFieldValue('quantity') || 0) + 1,
                    });
                  }}
                >
                  增加
                </Button>
                <Button
                  className="ml10"
                  onClick={() => {
                    productConfirmForm.setFieldsValue({
                      quantity: (productConfirmForm.getFieldValue('quantity') || 0) - 1,
                    });
                  }}
                >
                  减少
                </Button>
              </div>
            </div>

            <Form.Item>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </Modal>
    </>
  );
};

export default AddOrderProductCard;
